package com.example.pest.cos;

import cn.hutool.json.JSONUtil;
import com.example.pest.bean.PTResult;
import com.example.pest.service.impl.XxUserServiceImpl;
import com.example.pest.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Order(2)
@Component
@WebFilter(urlPatterns = "/**", filterName = "LoginFilter")
@AllArgsConstructor
public class LoginFilter implements Filter {

    private final XxUserServiceImpl userService;

    public static final List<String> passList = new ArrayList<String>(){{
        add("/login");
        add("/register");
        add("/code");
        add("/upload");
        add("/download");
    }};


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        if (!reqs.getMethod().contains("OPTION")) {
            String url = reqs.getRequestURI();
            if (isPass(url)) {
                chain.doFilter(req, res);
                return;
            }else {
              String jwt =  reqs.getHeader("JWT");
               try {
                   JwtUtil.verifyToken(jwt);
                   if (url.contains("/manage/") &&  JwtUtil.isConsume()){
                       PTResult result = new PTResult<>(4004,"无权访问",null);
                       response.getOutputStream().write(JSONUtil.toJsonStr(result).getBytes("utf-8"));
                       return;
                   }
               }catch (Exception e){
                    PTResult result = new PTResult<>(4003,"未登陆",null);
                    response.getOutputStream().write(JSONUtil.toJsonStr(result).getBytes("utf-8"));
                    return;
               }
            }
        }
        chain.doFilter(req, res);
    }

    public boolean isPass(String url){
        for (String str : passList){
            if (url.contains(str)){
                return true;
            }
        }
        return false;
    }
    @Override
    public void init(FilterConfig filterConfig) {
    }
    @Override
    public void destroy() {}
}

